﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Collections.ObjectModel;
using System.Windows.Data;

using AcAp = Autodesk.AutoCAD.ApplicationServices.Application;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.EditorInput;
using System.Reflection;
using Autodesk.AutoCAD.Runtime;


namespace haimian
{
    /// <summary>
    /// 海绵城市的种类样式
    /// </summary>
    public enum GroundType
    {
        /// <summary>
        /// 生物滞留池
        /// </summary>
        Biological,
        /// <summary>
        /// 下凹式绿地
        /// </summary>
        LowImpact,
        /// <summary>
        /// 雨水调蓄池
        /// </summary>
        Rainwater,
        /// <summary>
        /// 透水铺装
        /// </summary>
        Permeable
    }


    class PattlePanelViewModel : INotifyPropertyChanged
    {
         GroundType m_groundType;
         int m_number;
         double m_area;
         double m_height;
         double m_volume;
         readonly List<GroundInfo> m_groundList;
         string m_groundName; 

        // 初始化参数
         public PattlePanelViewModel()
         {
             m_groundList = new List<GroundInfo> 
            { 
                new GroundInfo{ Name="生物滞留池", Type=GroundType.Biological},
                new GroundInfo{ Name="下凹式绿地", Type=GroundType.LowImpact},
                new GroundInfo{ Name="雨水调蓄池", Type=GroundType.Rainwater},
                new GroundInfo{ Name="透水铺装", Type=GroundType.Permeable}
            };
             m_number = 1;
             m_area = 0.0;
             m_height = 100.0;
             m_groundName = "下凹式绿地";
         }

        // 海绵城市类型
        public GroundType GroundType
        {
            get { return m_groundType;  }
            set
            {
                if (value != m_groundType )
                {
                    m_groundType = value;
                    Notify("GroundType");
                }
            }
        }

        // 海绵城市类型信息类
        public class GroundInfo
        {
            public GroundType Type { get; set; }
            public string Name { get; set; }
        }

        // 海绵城市类型信息列表
        public List<GroundInfo> GroundList
        {
            get { return m_groundList; }
        }

        // 设施名称
        public string GroundName
        {
            get { return m_groundName; }
            set
            {
                if (value != m_groundName)
                {
                    m_groundName = value;
                    Notify("GroundName");
                }
            }
        }

        // 数字编号
        public int Number
        {
            get { return m_number; }
            set
            {
                if (value != m_number)
                {
                    m_number = value;
                    Notify("Number");
                }
            }
        }

        // 面积
        public double Area
        {
            get { return m_area; }
            set
            {
                if (value != m_area)
                {
                    m_area = Math.Round(value, 1);
                    Notify("Area");
                    Notify("Volume");
                }
            }
        }

        // 有效深度
        public double Height
        {
            get { return m_height; }
            set
            {
                if (value != m_height)
                {
                    m_height = Math.Round(value,1);
                    Notify("Height");
                    Notify("Volume");
                }
            }
        }

        // 有效容积
        public double Volume
        {
            get
            {
                if (m_area != 0.0D)
                {
                    return m_area * m_height / 1000;
                }
                return 0.0;
            }
            set
            {
                if (value != m_volume)
                {
                    m_volume = Math.Round(value, 2);
                    Notify("Volume");
                }
            }
        }

        // 获取LID面积的命令
        public RelayCommand GetAreaCommand
        {
            get
            {
                return new RelayCommand((_) => GetArea(), (_) => true);
            }
        }

        // 绘制表格的命令
        public RelayCommand AddTableCommand
        {
            get
            {
                return new RelayCommand((_) => AddTable(), (_) => true);
            }
        }



        // 获取实体ID的面积
        private void GetArea()
        {
            Document doc = AcAp.DocumentManager.MdiActiveDocument;
            Database db = doc.Database;
            Editor ed = doc.Editor;
            var entRes = ed.GetEntity("\n请选择要统计面积的物体：\n");
            if (entRes.Status == PromptStatus.OK)
            {
                Area = getEntityInfo(entRes.ObjectId, ed);
            }
        }

        // 获取Entity Id的面积
        private double getEntityInfo(ObjectId id, Editor ed)
        {
            BindingFlags flags = BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly;
            var res = 0.0;
            using (Transaction tr = id.Database.TransactionManager.StartTransaction())
            {
                var dbObj = tr.GetObject(id, OpenMode.ForRead);
                var types = new List<Type>();
                types.Add(dbObj.GetType());
                while (true)
                {
                    var type = types[0].BaseType;
                    types.Insert(0, type);
                    if (type == typeof(RXObject))
                        break;
                }
                foreach (Type t in types)
                {
                    if (t.Name == "Hatch" || t.Name == "Curve")
                    {
                        foreach (var prop in t.GetProperties(flags))
                        {
                            if (prop.Name == "Area")
                            {
                                try
                                {
                                    res = (double)prop.GetValue(dbObj, null);
                                }
                                catch (System.Exception e)
                                {
                                    ed.WriteMessage(e.Message);
                                }
                            }
                        }
                    }
                }
                tr.Commit();
            }
            return res;
        }

        // 添加海绵城市表格
        private void AddTable()
        {
            Document doc = AcAp.DocumentManager.MdiActiveDocument;
            Database db = doc.Database;
            Editor ed = doc.Editor;

            PromptPointResult ppr = ed.GetPoint("\n请选择表格插入点:");
            if (ppr.Status != PromptStatus.OK) return;


            using (DocumentLock docLock = doc.LockDocument())
            {
                using (Transaction trans = db.TransactionManager.StartTransaction())
                {
                    string LID = "";

                    ObjectId styleId = AddTableStyle("HaiMianTable");
                    Table table = new Table();
                    table.TableStyle = styleId;
                    table.Position = ppr.Value;
                    table.SetSize(5, 2);
                    table.SetRowHeight(3);
                    table.SetColumnWidth(10);
                    table.UnmergeCells(table.Rows[0]);
                    table.Cells[0, 0].TextString = "编号";
                    table.Cells[1, 0].TextString = "设施名称";

                    switch (GroundName)
                    {
                        case "生物滞留池":
                            LID = string.Format("H-{0}", Number);
                            table.Cells[2, 0].TextString = "设施面积(m" + TextSpecialSymbol.Square + ")";
                            table.Cells[3, 1].TextString = Height.ToString();
                            break;
                        case "下凹式绿地":
                            LID = string.Format("X-{0}", Number);
                            table.Cells[2, 0].TextString = "设施面积(m" + TextSpecialSymbol.Square + ")";
                            table.Cells[3, 1].TextString = Height.ToString();
                            break;
                        case "雨水调蓄池":
                            LID = string.Format("Y-{0}", Number);
                            table.Cells[2, 0].TextString = "汇水面积(m" + TextSpecialSymbol.Square + ")";
                            break;
                        case "透水铺装":
                            LID = string.Format("T-{0}", Number);
                            table.Cells[2, 0].TextString = "设施面积(m" + TextSpecialSymbol.Square + ")";
                            table.Cells[3, 1].TextString = Height.ToString();
                            break;
                        default:
                            ed.WriteMessage("\n请选择设施！\n");
                            return;
                    }

                    table.Cells[3, 0].TextString = "有效深度(mm)";
                    table.Cells[4, 0].TextString = "有效容积(m" + TextSpecialSymbol.Cube + ")";


                    table.Cells[0, 1].TextString = LID;
                    table.Cells[1, 1].TextString = GroundName;
                    table.Cells[2, 1].TextString = Area.ToString();
                    table.Cells[4, 1].TextString = Volume.ToString();

                    db.AddToModelSpace(table);

                    this.Number += 1;
                    trans.Commit();
                }
            }
        }

        //为当前图形添加一个新的表格样式
        public static ObjectId AddTableStyle(string style)
        {
            ObjectId styleId; // 存储表格样式的Id
            Database db = HostApplicationServices.WorkingDatabase;
            using (Transaction trans = db.TransactionManager.StartTransaction())
            {
                // 打开表格样式字典
                DBDictionary dict = (DBDictionary)db.TableStyleDictionaryId.GetObject(OpenMode.ForRead);
                if (dict.Contains(style)) // 如果存在指定的表格样式
                    styleId = dict.GetAt(style); // 获取表格样式的Id
                else
                {
                    TableStyle ts = new TableStyle(); // 新建一个表格样式

                    ts.IsHeaderSuppressed = true;
                    ts.IsTitleSuppressed = false;

                    // 设置表格所有行的外边框的线宽为0.30mm
                    ts.SetGridLineWeight(LineWeight.LineWeight030, (int)GridLineType.OuterGridLines, TableTools.AllRows);
                    // 不加粗表格数据行的顶部边框
                    ts.SetGridLineWeight(LineWeight.LineWeight000, (int)GridLineType.HorizontalTop, (int)RowType.DataRow);
                    // 设置表格中所有行的文本高度为1
                    ts.SetTextHeight(1, TableTools.AllRows);
                    // 设置表格中所有行的对齐方式为正中
                    ts.SetAlignment(CellAlignment.MiddleLeft, TableTools.AllRows);
                    dict.UpgradeOpen();//切换表格样式字典为写的状态
                    // 将新的表格样式添加到样式字典并获取其Id
                    styleId = dict.SetAt(style, ts);
                    // 将新建的表格样式添加到事务处理中
                    trans.AddNewlyCreatedDBObject(ts, true);
                    trans.Commit();
                }
            }
            return styleId; // 返回表格样式的Id
        }




        // 数据绑定相关
        public event PropertyChangedEventHandler PropertyChanged;
        private void Notify(string propertyName)
        {
            if (PropertyChanged != null)
            {
                this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }
}
